<script setup lang="ts">
import {get,put,del,post} from "@/axios"
import {onMounted, reactive, ref,toRaw,computed,nextTick,watch} from "vue"
import {User} from "@element-plus/icons-vue";
import UserInter from "@/type/user-inter.ts";
import {verifyUserAuthority} from "@/utils/VerifyUserAuthority.ts";
import {ComponentSize, ElMessage} from "element-plus";

const page = ref(1)
const size = ref(10)
const userList = reactive([])
const editOrInsert = ref(false)
const userPanel = ref(false)
const userForm = reactive<UserInter>({})
const ruleList = reactive([])
const pageInfo = reactive({
  total:0,
  pageTotal:0,
})
const loading = ref(false)
const ruleSelect = ref([])
const userDetailVis = ref(false)
const userDetail = ref({})
const contextMenuVisible = ref(false)
const contextMenuPosition = reactive({
  contextMenuTop: 0,
  contextMenuLeft: 0,
})
const userPosts = ref({})
const editPostsVis = ref(false)

const FirstDepartment = ref()
const SecondDepartment = ref("")
const UserPosts = ref("")

const departmentList = reactive([])
const secondDepartmentList = ref([])
const postList = ref([])

const ComSize = ref<ComponentSize>('default')

const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px',
  }
  return {
    marginRight: marginMap[ComSize.value] || marginMap.default,
  }
})
const blockMargin = computed(() => {
  const marginMap = {
    large: '32px',
    default: '28px',
    small: '24px',
  }
  return {
    marginTop: marginMap[ComSize.value] || marginMap.default,
  }
})

const reloadUserList = (pageNum?:number) => {
  get(`/User/GetUserList?page=${page.value}&&size=${size.value}`).then((res: any) => {
    if (res.status == 200) {
      pageInfo.total = res.data.totalCount
      pageInfo.pageTotal = res.data.totalPages
      if(page.value == 1){
        Object.assign(userList,res.data)
      }else {
        new Promise((resolve)=>{
          userList.splice(0,userList.length)
          resolve(true)
        }).then((e)=>{
          if (e){
            Object.assign(userList,res.data)
          }
        })
      }
    }
    get("/Department/GetDepartment").then((res:any)=> {
      if(res.status == 200){
        Object.assign(departmentList,res.data)
      }
    })
  })  
  get(`/Rule/GetRuleList`).then((res:any)=> {
    if(res.status == 200){
      Object.assign(ruleList,res.data);
    }
  })
}
const indexMethod = (index: number)=>{
  return index+=1
}

const banUserFunc = (data:UserInter)=>{
  console.log(data)
  //为真即禁用
  if(data.isActive){
    verifyUserAuthority().then((res:any)=>{
      if(res){
        put(`/User/BanUser?id=${data.userId}`).then((res:any)=>{
          if (res.status == 200) {
          } else {
            data.isActive = !data.isActive
          }
        })
      }else {
        ElMessage.error("身份认证失败！")
      }
    }).catch((res)=>{
      data.isActive = !data.isActive
    })
  }else {
    verifyUserAuthority().then((res:any)=>{
      if(res){
        put(`/User/EnableUser?id=${data.userId}`).then((res:any)=>{
          if (res.status == 200) {

          }else {
            data.isActive = !data.isActive
          }
        })
      }else {
        ElMessage.error("身份认证失败！")
      }
    }).catch((res)=>{
      data.isActive = !data.isActive
    })
  }
}

const addUserFunc = ()=>{
  editOrInsert.value = true
  userPanel.value = true
  Object.assign(userForm,{
    id: "",
    username: "",
    password: "",
    email: "",
    phone: "",
    isActive: false,
    isDeleted: false,
    createDate: "",
    banDate: "",
    deleteDate: "",
    rules:[],
  })
}
const editUserFunc = (data:UserInter)=>{
  editOrInsert.value = false
  userPanel.value = true
  Object.assign(userForm,data)
  console.log("data",data)
  ruleSelect.value = data.rules.map(item => item.id)
}
const deleteUserFunc = (row:any)=>{
  verifyUserAuthority().then((res:any)=>{
    if(res){
      del(`/User/DeleteUser?id=${row.userId}`).then((res:any)=>{
        if(res.status == 200){
          reloadUserList()
        }
      })
    }else {
      ElMessage.error("身份认证失败！")
    }
  })
}

const onSubmit = (type:string)=>{
  userForm.rules = ruleSelect.value
  const user = toRaw(userForm)
  if (editOrInsert.value) {
    post("/User/AddUser", user).then((res: any) => {
      if (res.status === 200) {
        userPanel.value = false
        Object.assign(userList,res.data)
        reloadUserList()
      }
    })
  } else {
    put("/User/UpdateUser", user).then((res: any) => {
      if (res.status === 200) {
        ElMessage.success("修改成功")
        userPanel.value = false
        reloadUserList()
      }
    })
  }
  
}

onMounted(()=>{
  reloadUserList()
})
const blurRuleFunc = ()=>{
  if(!editOrInsert.value){
    userForm.rules = []
  }
}
const checkUserFunc = async (data)=>{
  console.log("1",data)
  await get(`/User/GetUserDetail?id=${data.userId}`).then((res:any)=>{
    if (res.status === 200){
      console.log("2",res.data)
      Object.assign(userDetail.value,res.data[0])
    }
  })
  await nextTick()
    console.log("3")
    userDetailVis.value = true
    console.log(userDetail)
}
const cancelUserPanel = () => {
  userPanel.value = false
  //Object.assign(ruleSelect,[])
}

const openContextMenu = (row, column, event)=>{
  event.preventDefault();
  contextMenuPosition.contextMenuTop = event.pageY - 100 + 'px'
  contextMenuPosition.contextMenuLeft = event.pageX - 150 + 'px'
  contextMenuVisible.value = true
  userPosts.value = row
}
const editUserPosts = (event)=> {
    contextMenuVisible.value = false
    editPostsVis.value = true
}

const getPostByDepartmentId = (id:string)=> {
  get(`/Posts/GetPostByDepartment?department=${id}`).then((res:any)=>{
    if(res.status == 200){
      postList.value = res.data.items
    }
  })
}

const handleClose = ()=> {
  
}
const submitPosts = ()=>{
    post("/User/AddUserPost",{
      userId:userPosts.value.userId ,
      postsId:UserPosts.value
    }).then((res:any)=>{
      if(res.status == 200){
        editPostsVis.value = false
        contextMenuVisible.value = false
      }
    }).catch((e:any)=>{
      ElMessage.error("添加失败,请检查该用户是否已经安排了岗位!")
      contextMenuVisible.value = false
    })
}
  
watch(FirstDepartment,(value)=>{
  secondDepartmentList.value = []
    departmentList.forEach((item)=> {
      if(item.id == value){
        secondDepartmentList.value.push(...item.childDepartments)
      }
    })
    SecondDepartment.value = ""
    getPostByDepartmentId(value)
})

watch(SecondDepartment,(value)=>{
  postList.value = []
  UserPosts.value = ""
  getPostByDepartmentId(value)
})

</script>

<template>
  <div class="user-list-container">
    <div class="user-table">
      <div class="title">
        <span>用户列表</span>
        <el-button type="success" @click="addUserFunc">添加用户</el-button>
      </div>
      <el-table
          @row-contextmenu="openContextMenu"
          :data="userList" 
          style="width: 100%">
        <el-table-column label="序号" width="60" type="index" :index="indexMethod" />
        <el-table-column label="用户名" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-icon>
                <user/>
              </el-icon>
              <span style="margin-left: 10px">{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="180"/>
        <el-table-column prop="email" label="邮箱" width="180"/>
        <el-table-column prop="createDate" label="创建时间" width="180"/>
        <el-table-column prop="isActive" label="是否封禁" width="60">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-switch 
                  v-model="scope.row.isActive"
                  @change="banUserFunc(scope.row)"></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="180">
          <template #default="{ row }">
            <div v-if="row.rules.length !=0">
                <div v-for="item in row.rules" style="display: inline-block;margin-left: 5px;">
                  <el-tag type="success">
                    {{ item.name }}
                  </el-tag>
                </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="240">
          <template #default="scope">
            <el-button @click="checkUserFunc(scope.row)">查看</el-button>
            <el-button type="primary" @click="editUserFunc(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteUserFunc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
          v-model:page-size="size" 
          background 
          hide-on-single-page l
          ayout="prev, pager, next" 
          :total="pageInfo.total"
          :page-count="pageInfo.pageTotal"
          v-model:current-page="page"
          @current-change="reloadUserList"
      />
    </div>
  </div>
  <el-dialog v-model="userPanel"
             :title="editOrInsert? '新增用户':'编辑用户'" width="800">
    <el-form
        label-position="left"
        :model="userForm"
        label-width="auto"
        style="max-width: 600px">
      <el-form-item label="用户名" :required="true">
        <el-input v-model="userForm.username"/>
      </el-form-item>
      <el-form-item label="密码" :required="true">
        <el-input type="password" v-model="userForm.password"/>
      </el-form-item>
      <el-form-item label="手机号码" :required="true">
        <el-input v-model="userForm.phone"/>
      </el-form-item>
      <el-form-item label="邮箱" :required="true">
        <el-input v-model="userForm.email"/>
      </el-form-item>
      <el-form-item label="分配权限角色" :required="true">
        <el-select
            v-model="ruleSelect"
            placeholder="请输入关键字"
            multiple
            :loading="loading"
            style="width: 240px"
            @focus="blurRuleFunc"
        >
          <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="cancelUserPanel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog
      class="user-details"
      v-model="userDetailVis"
      title="用户详情"
      width="900"
  >
    <el-descriptions
        class="margin-top"
        title="用户信息"
        :column="3"
        :size="size"
        border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <user />
            </el-icon>
           用户名：
          </div>
        </template>
       {{userDetail.username}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <iphone />
            </el-icon>
            手机号
          </div>
        </template>
        {{userDetail.phone}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <location />
            </el-icon>
            邮箱
          </div>
        </template>
        {{userDetail.email}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            入职时间：
          </div>
        </template>
        {{userDetail.createDate}}
      </el-descriptions-item>
      <el-divider />
    </el-descriptions>
    <el-descriptions
        style="margin-top: 5px"
        class="margin-top"
        title="用户角色"
        :column="3"
        :size="size"
        border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            角色：
          </div>
        </template>
        <div v-if="userDetail.rules.length != 0">
          <el-tag type="success" v-for="rule in userDetail.rules" :key="rule.id">{{rule.name}}</el-tag>
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions
        v-if="userDetail.department.parentDepartment"
        style="margin-top: 5px"
        class="margin-top"
        title="用户部门"
        :column="3"
        :size="size"
        border
    >
      <el-descriptions-item >
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            部门：
          </div>
        </template>
          <el-tag type="primary">{{userDetail.department.parentDepartment.name?userDetail.department.parentDepartment.name:""}}</el-tag>
          &gt<el-tag type="success">{{userDetail.department.userDepartment.name?userDetail.department.userDepartment.name:""}}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item v-if="userDetail.post">
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            岗位：
          </div>
        </template>
        {{userDetail.post.name}}
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>

  <el-dialog
      title="编辑用户岗位"
      v-model="editPostsVis"
      width="50%"
      @close="handleClose">
    <div class="selected-posts">
      <el-select class="select-item" v-model="FirstDepartment" placeholder="选择顶级部门">
        <el-option
            v-for="item in departmentList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-select class="select-item" v-model="SecondDepartment" placeholder="选择二级部门">
        <el-option
            v-for="item in secondDepartmentList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-select class="select-item" v-model="UserPosts" placeholder="选择岗位">
        <el-option
            v-for="item in postList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
    </div>
    <div class="submit-posts">
      <el-button type="primary" @click="submitPosts">提交</el-button>
    </div>
  </el-dialog>

  <!-- 自定义菜单 -->
  <div
      v-show="contextMenuVisible"
      :style="{ top: contextMenuPosition.contextMenuTop , left: contextMenuPosition.contextMenuLeft ,'z-index':1000}"
      class="custom-context-menu"
  >
    <el-button @click="editUserPosts">编辑用户岗位</el-button>
  </div>
</template>

<style scoped>
.user-list-container {
  width: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
}
.user-table {
  width: 1500px;
  background-color: white;
  font-size: 18px;
}
.title{
  font-size: 20px;
  color: #283443;
  margin: 10px 5px;
  display: flex;
  justify-content: space-between;
}
.custom-context-menu{
  position: absolute;
  padding: 15px 15px;
  background-color: #f8f8f8;
}
.selected-posts{
  display: flex;
  justify-content: space-between;
}
.select-item{
  margin-left: 10px;
}

.submit-posts{
  margin-top: 10px;
  margin-left: 10px;
}
</style>